import { getAddressAuth } from '@/common/api/address'

const state = {
  province: [],
  addressMap: {},
}

const getters = {
  province: state => state.province,
}

const actions = {
  async getAddress({ commit }, { address, level, force = false, config }) {
    if (!force) {
      if (level === 0) {
        if (state.province.length) return state.province
      } else {
        const stateAddress = state.addressMap[address]
        if (stateAddress && stateAddress.length) return stateAddress
      }
    }

    const fetchFn = getAddressAuth(address, level, config)

    return fetchFn.then(res => {
      if (level === 0) {
        commit('province', res)
      } else {
        commit('addressMap', {
          address,
          children: res,
        })
      }

      return res
    })
  },
}

const mutations = {
  province: (state, payload) => (state.province = payload),
  addressMap: (state, payload) => (state.addressMap[payload.address] = payload.children),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
